package zhang.test.dataSourceConfig;

import com.alibaba.druid.pool.DruidDataSource;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.support.GenericWebApplicationContext;
import zhang.test.DatasourceShuxing.GongxianData;

import javax.sql.DataSource;


@Configuration
public class MybatisSource implements ApplicationContextAware{


    @Autowired
    private GongxianData a;  //数据源共享属性

    private GenericWebApplicationContext c;

    private HikariConfig h=new HikariConfig();  //海卡瑞数据源构造参数


    /**
     * 手动注入数据源
     * @return
     */

    @Bean
    public DataSource pooleddatasource(){

        return new PooledDataSource(a.getDriver(),a.getUrl(),a.getUsername(),a.getPassword());
    }


    /**
     * 数据源切换....
     * @param datasourceClassname
     * @return
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public boolean DatasourceQiehuan(Class datasourceClassname) throws IllegalAccessException, InstantiationException {

        String[] beanNamesForType = c.getBeanNamesForType(DataSource.class);
        for (String s:beanNamesForType){
            c.removeBeanDefinition(s);
        }

        if (datasourceClassname==HikariDataSource.class){  //海卡瑞
            h.setUsername(a.getUsername());
            h.setPassword(a.getPassword());
            h.setJdbcUrl(a.getUrl());
            h.setDriverClassName(a.getDriver());
            c.registerBean(datasourceClassname,h);
            return c.containsBean(datasourceClassname.getName());

        }
        if (datasourceClassname==PooledDataSource.class){  //连接池数据源
            c.registerBean(datasourceClassname,a.getDriver(),a.getUrl(),a.getUsername(),a.getPassword());
            return c.containsBean(datasourceClassname.getName());

        }
        if (datasourceClassname==DruidDataSource.class){ //德鲁伊数据源
            c.registerBean(datasourceClassname);
            DruidDataSource bean = c.getBean(DruidDataSource.class);
            bean.setDriverClassName(a.getDriver());
            bean.setUrl(a.getUrl());
            bean.setUsername(a.getUsername());
            bean.setPassword(a.getPassword());
            return c.containsBean(datasourceClassname.getName());

        }

        return false;
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        c=(GenericWebApplicationContext)applicationContext;

    }
}
